package com.sgb.kjwl.view.ui.fragment.manage

import android.os.Bundle
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener
import com.scwang.smart.refresh.layout.listener.ScrollBoundaryDecider
import com.sgb.kjwl.AppLazyFragment
import com.sgb.kjwl.R
import com.sgb.kjwl.databinding.FragmentAgentStaffCheckBinding
import com.sgb.kjwl.databinding.ItemAgentCustomerCheckBinding
import com.sgb.kjwl.di.self.DaggerSelfFragComponent
import com.sgb.kjwl.di.self.SelfFragModule
import com.sgb.kjwl.viewmodel.manage.AgentCheckModel
import com.sgb.member.entity.MemberAuditBean
import com.swgk.core.base.di.AppComponent
import javax.inject.Inject

class AgentCustomerCheckFragment : AppLazyFragment(){
    private lateinit var mBinding : FragmentAgentStaffCheckBinding

    @Inject
    lateinit var mViewModel : AgentCheckModel

    private var isLoadMore = false // 是否是加载更多
    private lateinit var mAdapter : AgentCustomerCheckAdapter

    private var isEnableLoadMore = false //是否可以上拉加载

    private var isRefresh = false //返回页面是否需要刷新
    private var isFirst = false //是否第一次进来页面

    companion object {
        fun newInstance(): AgentCustomerCheckFragment {
            val fragment = AgentCustomerCheckFragment()
            val bundle = Bundle()
            fragment.arguments = bundle
            return fragment
        }
    }

    override fun onLazyLoad() {
        isLoadMore = false
        refreshDatas() //进去页面首次加载
        isRefresh = true
        isFirst = !isFirst
    }

    override fun setupFragmentComponent(appComponent: AppComponent?) {
        DaggerSelfFragComponent.builder().appComponent(appComponent)
            .selfFragModule(SelfFragModule()).build().inject(this)
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        mBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_agent_staff_check, container, false)
        return mBinding.root
    }

    override fun initView() {
        super.initView()
        mBinding.recycleView.layoutManager = LinearLayoutManager(context, RecyclerView.VERTICAL, false)
        // SwipeRefreshLayout 刷新
        mBinding.refreshLayout.setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener {
            override fun onLoadMore(refreshLayout: RefreshLayout) {
                isLoadMore = true
                refreshDatas()
                mBinding.refreshLayout.finishLoadMore(500)
            }

            override fun onRefresh(refreshLayout: RefreshLayout) {
                isLoadMore = false
                refreshDatas()
                mBinding.refreshLayout.finishRefresh(500)
            }
        })
        //解决 在实现 上拉加载更多 和 下拉刷新 时  遇到item不在顶端就执行了刷新的方法和数据item没有填满屏幕也执行了加载更多
        mBinding.refreshLayout.setScrollBoundaryDecider(object : ScrollBoundaryDecider {
            override fun canRefresh(content: View): Boolean {
                if (mBinding.recycleView == null) return false
                return mBinding.recycleView.computeVerticalScrollOffset() === 0
            }

            override fun canLoadMore(content: View): Boolean {
                if (mBinding.recycleView == null) return false
                //整个View控件的高度
                val scrollRange: Int = mBinding.recycleView.computeVerticalScrollRange()
                //当前屏幕之前滑过的距离
                val scrollOffset: Int = mBinding.recycleView.computeVerticalScrollOffset()
                //当前屏幕显示的区域高度
                val scrollExtent: Int = mBinding.recycleView.computeVerticalScrollExtent()
                //获取recyclerView的高度
                val height: Int = mBinding.recycleView.height
                if (height > scrollRange) {
                    return false
                }
                return isEnableLoadMore && scrollRange <= scrollOffset + scrollExtent
            }
        })
        mAdapter = AgentCustomerCheckAdapter(R.layout.item_agent_customer_check)
        mAdapter.bindToRecyclerView(mBinding.recycleView)
        val empty = LayoutInflater.from(context).inflate(R.layout.layout_empty_view, mBinding.recycleView, false)
        mAdapter.emptyView = empty
        mAdapter.onItemClickListener = object : BaseQuickAdapter.OnItemClickListener{
            override fun onItemClick(adapter: BaseQuickAdapter<*, *>?, view: View?, position: Int) {
                //跳转到H5界面
                val item = mAdapter.getItem(position);
                if (item != null) {
                 /*   if (item.getMemberType() == 2) {
                        var enrUrl =
                            "?no=" + item.getNo() + "&companyNo=" + item.getBusinessNo() + "&joinWay=" + item.getJoinWay()
                        if (item.getStatus() == 1) {
                            enrUrl += "&isExamine=1" // isExamine从会员审核列表进入传1
                        }
                        context?.let { mViewModel.getUrlSetting(it,"companyExamine", enrUrl) }
                    } else {
                        //跳转到H5界面
                        var enrUrl =
                            "?no=" + item.getNo() + "&userNo=" + item.getBusinessNo() + "&joinWay=" + item.getJoinWay()
                        if (item.getStatus() == 1) {
                            enrUrl += "&isExamine=1" // isExamine从会员审核列表进入传1
                        }
                        context?.let { mViewModel.getUrlSetting(it,"personalExamine", enrUrl) }
                    }*/
                    //跳转到H5界面
                    if (item.memberType == 1) {
                        var enrUrl =
                            "?no=" + item.no + "&companyNo=" + item.businessNo + "&joinWay=" + item.joinWay
                        if (item.status == 1) {
                            enrUrl += "&isExamine=1" // isExamine从会员审核列表进入传1
                        }
                        context?.let { mViewModel.getUrlSetting(it,"companyExamine", enrUrl) }
                    } else {
                        //跳转到H5界面
                        var enrUrl =
                            "?no=" + item.no + "&userNo=" + item.businessNo + "&joinWay=" + item.joinWay
                        if (item.status == 1) {
                            enrUrl += "&isExamine=1" // isExamine从会员审核列表进入传1
                        }
                        context?.let { mViewModel.getUrlSetting(it,"personalExamine", enrUrl) }
                    }
                }
            }
        }
        renderLifeCycle()
    }

    private fun renderLifeCycle() {
        mViewModel.checkDatas.observe(this, {
            isEnableLoadMore = it.size >= 10
            if (isLoadMore){
                mAdapter.addData(it)
            } else {
                mAdapter.setNewData(it)
            }
        })
    }

    override fun onResume() {
        super.onResume()
        if (!isFirst){
            if (isRefresh){
                isLoadMore = false //返回页面
                refreshDatas()
            } else {
                isFirst = true
            }
        } else {
            if (isRefresh){
                isFirst = false
            }
        }
    }

    //刷新
    private fun refreshDatas() {
      mViewModel.getMixAuditingMemberByPage(requireContext(), isLoadMore, "1")
    }


    class AgentCustomerCheckAdapter(layoutResId : Int) : BaseQuickAdapter<MemberAuditBean, BaseViewHolder>(layoutResId){
        private  var mItemBinging : ItemAgentCustomerCheckBinding?= null
        override fun convert(helper: BaseViewHolder?, item: MemberAuditBean?) {
            mItemBinging = DataBindingUtil.bind(helper!!.itemView)
            if (item != null) {
                if (mItemBinging != null) {
                    mItemBinging!!.viewModel = item
                    mItemBinging!!.executePendingBindings()
                }
                when (item.getStatus()) {
                    1 -> mItemBinging!!.auditStatus.setImageResource(R.mipmap.member_icon_dsh)
                    2 -> mItemBinging!!.auditStatus.setImageResource(R.mipmap.member_icon_passed)
                    3 -> mItemBinging!!.auditStatus.setImageResource(R.mipmap.member_icon_yjj)
                }
                if (!TextUtils.isEmpty(item.serviceTypeName)) {
                    mItemBinging!!.memberAuditType.text = item.serviceTypeName
                } else {
                    mItemBinging!!.memberAuditType.text = "-"
                }
            }

        }
    }

}